/*	Copyright 2008 Jacquemin Valentin

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
	
	@author pollux
 */
package org.poxd.persistance;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.poxd.model.Category;
import org.poxd.model.Language;

/**
 * @author pollux
 * 
 */
public class CategoriesDAO extends AbstractDAO {
	private static final Logger log = Logger.getLogger(CategoriesDAO.class);

	/**
	 * Returns the categories that contain a language
	 * 
	 * @param Language
	 *            l
	 * @return
	 */
	public Map<String, Category> getCategories(Language l) {
		startOperation();
		log.debug("GET CATEGORIES FOR LANGUAGE : " + l.getId());
		l = (Language) session.get(Language.class, l.getId());
		Map<String, Category> ret = null;
		if (l != null) {
			ret = l.getCategories();
			if (log.isDebugEnabled()) {
				if (ret != null && ret.keySet() != null
						&& ret.keySet().size() > 0)
					log.debug("CATEGORIES : "
							+ Arrays.toString(ret.keySet().toArray()));
			}
		}
		endOperation();
		return ret;
	}

	/**
	 * @param currentLanguage
	 * @param title
	 */
	public void addCategory(Language currentLanguage, String title) {
		startOperation();
		log.debug("ADD CATEGORY : " + title + " TO THE LANGUAGE "
				+ currentLanguage);
		Category c = new Category();
		c.setName(title);
		Language persisted = (Language) session.get(Language.class,
				currentLanguage.getId());
		if (persisted.getCategories() == null) {
			persisted.setCategories(new HashMap<String, Category>());
		}
		persisted.getCategories().put(title, c);
		session.saveOrUpdate(persisted);
		endOperation();
	}

	public void deleteCategory(Category source) {
		startOperation();
		log.debug("DELETE CATEGORY " + source);
		session.delete(source);
		endOperation();
	}
}
